﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Group3.Framework.Extensions
{
    public static class ExtensionsIEnumerable
    {

        /// <summary>
        /// Erzeugt aus der Enumeration ein Dictionary
        /// Die Funktion liefert das Key-Element des Dictionary
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TItem"></typeparam>
        /// <param name="list"></param>
        /// <param name="getkey"></param>
        /// <returns></returns>
        public static Dictionary<TKey, TItem> ToDictionary<TKey, TItem>(this IEnumerable<TItem> list, Func<TItem, TKey> getkey)
        {
            Dictionary<TKey, TItem> dict = new Dictionary<TKey, TItem>();
            if (list == null || list.Count() < 1) return dict;
            TKey key = default(TKey);
            foreach (var itm in list)
            {
                key = getkey(itm);
                if (!dict.ContainsKey(key)) dict.Add(key, itm);
            }
            return dict;
        }
        /// <summary>
        /// Iteration über alle Elemente (es wird die Action durchgeführt)
        /// Die Enumeration darf auch null sein.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="action"></param>
        public static void Each<T>(this IEnumerable<T> list, Action<T> action)
        {
            if (list != null && list.Count() > 0 && action != null)
                foreach (T itm in list)
                    action(itm);

        }
        /// <summary>
        /// Prüft ob ein Element vorkommt
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="checkrule"></param>
        /// <returns></returns>
        public static bool Exists<T>(this IEnumerable<T> list, Func<T, bool> checkrule)
        {
            if (list == null || list.Count() < 1 || checkrule == null) return false;
            return list.FirstOrDefault(itm => checkrule(itm)) != null;
        }
    }
}
